<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧商品、支付信息录入表单 -->
      <el-col :span="7" :xs="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>房间预定</span>
          </div>
          <el-form :model="queryParams" ref="form" size="small" label-width="68px">
            <el-form-item label="名字" prop="name">
            <el-input v-model="form.name" placeholder="请输入名字" clearable size="small"  :disabled="step !== 1"/>
          </el-form-item>
          <el-form-item label="身份证号" prop="nameId">
            <el-input v-model="form.nameId" placeholder="请输入身份证号" clearable size="small"  :disabled="step !== 1" />
          </el-form-item>
          <el-form-item label="房型" prop="categoryName">
            <el-input v-model="form.categoryName" placeholder="请输入房型" clearable size="small" :disabled="step !== 1" />
          </el-form-item>
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker v-model="form.startDate" type="date" size="small" style="width: 240px" placeholder="选择开始日期" :disabled="step !== 1" ></el-date-picker>
          </el-form-item>
          <el-form-item label="截止日期" prop="endDate">
            <el-date-picker v-model="form.endDate" type="date" size="small" style="width: 240px" placeholder="选择截止日期" :disabled="step !== 1"></el-date-picker>
          </el-form-item>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-button type="primary" size="mini" :disabled="step !== 1" @click="submitForm">提交</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="warning" size="mini" :disabled="step !== 1" @click="endSale">结算</el-button>
            </el-col>
          </el-row>
          </el-form>
        </el-card>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>订单支付</span>
          </div>
          <el-form :model="makePaymentForm" ref="makePaymentForm" size="small" label-width="68px">
            <el-form-item label="付款金额" prop="cashTendered">
              <el-input v-model="makePaymentForm.cashTendered" type="number" :disabled="step !== 3" ></el-input>
            </el-form-item>
            <el-form-item label="找零">
              <el-input v-model="changeDue" disabled></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" size="mini" :disabled="step !== 3" @click="makePayment">支付</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧商品、支付信息录入表单 -->
      <el-col :span="17" :xs="24">
        <el-descriptions border>
          <template slot="extra">
            <el-button type="success" size="small" round :disabled="step!==3" @click="makeNewSale">办理预定</el-button>
          </template>
          <el-descriptions-item label="入住人">{{form.name}}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{form.nameId}}</el-descriptions-item>
          <el-descriptions-item label="总金额">{{form.total}}</el-descriptions-item>
          <el-descriptions-item label="房号">{{form.roomId}}</el-descriptions-item>
          <el-descriptions-item label="房型"><el-tag size="small">{{form.categoryName}}</el-tag></el-descriptions-item>
          <el-descriptions-item label="备注">暂无</el-descriptions-item>
        </el-descriptions>
        <br>
        <el-card class="box-card">
        <!-- 数据展示Table -->
        <div slot="header" class="clearfix">
          <span>订单明细</span>
        </div>
        <el-table v-loading="loading" :data="dataList" >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="订单号" prop= "saleId" align="center" />
          <el-table-column label="房型" prop="category.categoryName" align="center"/>
          <el-table-column label="房号" prop="roomId" align="center"/>   
          <el-table-column label="预订人" prop="name" align="center"/>
          <el-table-column label="身份证号" prop="nameId" align="center"/>
          <el-table-column label="开始日期" prop="startDate" align="center"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="small" type="text" icon="el-icon-s-home" @click="handleCheckin(scope.row)">入住</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

         <!-- 分页加载 -->
         <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="queryParams.pageNum"
         :page-sizes="[5, 10, 20, 50]"
         :page-size="queryParams.pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total"
         >
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

  
  <script>
  import { listSale, makeCheckIn, addSale, makePayment, provideRoom } from "@/api/sale"
  export default {
    name: "Sale",
    // 定义属性
    data() {
      return {
        // 当前步骤，用于控制按钮是否可用
        step: 1,
        //找零
        changeDue: 0,
        //日期选择
        pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
        // 遮罩层
        loading: false,
        // 表格数据
        dataList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 5,
        },
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 勾选1个或多个
        multiple: true,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单
        form: {},
        makePaymentForm: {},
        // radio: '1',
        rules: {},
        // 总条数
        total: 0,
      }
    },
    // 计算属性，可选
    computed: {},
    // 监控data变化，可选
    watch: {},
    // 生命周期-创建完成，可选
    created() {
      this.getSaleList();
      this.getCategoryList();
    },
    // 生命周期-挂载完成，可选
    mounted() {},
    methods: {
      
      /** 分配房间 */
    //   getProvideRoom() {
    //   provideRoom(this.form.categoryName)
    //     .then(response => {
    //       // Assuming response.data contains the categoryId
    //       this.form.roomId = response.data.roomId;
    //     })
    //     .catch(error => {
    //       console.error("Error providing room:", error);
    //       // Handle error if needed
    //     });
    // },

      /** 查询数据列表 */
      getSaleList() {
        this.loading = true;
        // 结果赋值this.dataList
        listSale(this.queryParams).then(response => {
          this.dataList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        })
      },

      /** 入住按钮操作 */
      handleCheckin(row) {
        const saleId = row.saleId || this.ids;
        this.$confirm('是否确认办理订单号为"' + saleId + '"入住?',"办理入住",{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "checkin",
        }).then(() => {
        // 构建需要传递给后端的数据对象
        const data = {
        // 如果还有其他需要传递的字段，可以在这里添加
        saleId: row.saleId, 
        roomId: row.roomId,
        };
        // 调用后端的 makeCheckIn 方法
        makeCheckIn(data).then(response => {
          // 处理后端返回的结果
          if (response.code === 200) {
            this.$message.success(response.msg);
            // 成功办理入住后刷新数据列表
            this.getSaleList();
            this.cancel(); 
          } else {
            this.$message.error(response.msg || '办理入住失败');
          }
        }).catch(error => {
          console.error('办理入住失败:', error);
          this.$message.error('办理入住失败，请重试');
        });
      }).catch(() => {
        // 用户取消操作，不做任何处理
      });
    },
     /** 表单初始化 */
     resetForm() {
        // 可进行数据初始化工作
      this.form = {
        name: null,
        nameId: null,
        roomId: null,
        startDate: null,
        endDate: null,
        total: null,
      }
    },
    //步骤4：创建订单
    makeNewSale() {
        this.clear();
        this.step = 1;
      },
    // 步骤1：提交输入
    /** 提交按钮 */
    submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
              addSale(this.form).then(response => {
                this.$message.success(response.msg);
                this.form.total = response.data.total;
                this.form.roomId = response.data.roomId;
                this.getSaleList();
                // this.cancel();
              })
          }
        });
      },
      /** 取消按钮 */
      cancel() {
        this.title = "";
        this.resetForm();
      },
      // 步骤2：结束输入
      endSale(){
        this.step = 3;
      },
      // 步骤3：提交支付
      makePayment: function() {
      // 获取用户输入的付款金额
      const cash = this.makePaymentForm.cashTendered;
      // 调用后端接口发送付款金额
      makePayment(cash).then(change => {
        // 接收后端返回的找零金额，并更新前端显示
        console.log(change);
        this.changeDue = change.data;
        // 可以在此处执行其他操作，例如更新订单状态等
      }).catch(error => {
        // 处理错误
        console.error('Error making payment:', error);
        // 可以显示错误信息给用户
        this.$message.error('支付失败，请稍后重试。');
      });
      this.resetForm();
    },
    // 清空界面数据
    clear(){
          this.makePaymentForm = {
              cashTendered: 0
          };
          this.changeDue = 0;
          this.step = 1;
      },

       /** 处理分页 */
       handleSizeChange(val) {
        this.queryParams.pageSize = val;
        this.getSaleList();
      },
      handleCurrentChange(val) {
        this.queryParams.pageNum = val;
        this.getSaleList();
      },

      
    },
    
  }
  </script>

<style scoped lang="scss">

</style>
